<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getHotelById, getHotelRooms, createRoom, updateRoom, deleteRoom } from '../../api/hotel'

const route = useRoute()
const router = useRouter()
const hotelId = computed(() => Number(route.params.hotelId))

// 酒店信息
const hotelInfo = ref({
  hotelID: 0,
  name: '',
  address: '',
  starRating: 0
})

// 房间列表数据
const roomList = ref([])
// 加载状态
const loading = ref(false)

// 对话框显示控制
const dialogVisible = ref(false)
const dialogTitle = ref('添加房间')
const isEdit = ref(false)

// 房间状态选项
const roomStatusOptions = [
  { value: '空闲', label: '空闲' },
  { value: '已预订', label: '已预订' },
  { value: '已入住', label: '已入住' },
  { value: '维修中', label: '维修中' }
]

// 表单数据
const formData = reactive({
  roomID: 0,
  roomType: '',
  price: 0,
  status: '空闲',
  hotelID: hotelId.value
})

// 表单校验规则
const rules = {
  roomType: [
    { required: true, message: '请输入房间类型', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2到30个字符之间', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入房间价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择房间状态', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref()

// 获取酒店信息
const fetchHotelInfo = async () => {
  try {
    const res = await getHotelById(hotelId.value)
    hotelInfo.value = res.data
    document.title = `房间管理 - ${hotelInfo.value.name}`
  } catch (error) {
    console.error('获取酒店信息失败', error)
    ElMessage.error('获取酒店信息失败')
    router.push('/dashboard/hotels')
  }
}

// 获取房间列表
const fetchRooms = async () => {
  try {
    loading.value = true
    const res = await getHotelRooms(hotelId.value)
    roomList.value = res.data
  } catch (error) {
    console.error('获取房间列表失败', error)
    ElMessage.error('获取房间列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchHotelInfo()
  fetchRooms()
})

// 返回酒店列表
const backToHotels = () => {
  router.push('/dashboard/hotels')
}

// 打开添加房间对话框
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加房间'
  isEdit.value = false
  formData.hotelID = hotelId.value
  dialogVisible.value = true
}

// 打开编辑房间对话框
const handleEdit = (row: any) => {
  resetForm()
  dialogTitle.value = '编辑房间'
  isEdit.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.roomID = 0
  formData.roomType = ''
  formData.price = 0
  formData.status = '空闲'
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑房间
          await updateRoom(formData.roomID, {
            roomType: formData.roomType,
            price: formData.price,
            status: formData.status
          })
          ElMessage.success('更新房间成功')
        } else {
          // 添加房间
          await createRoom({
            roomType: formData.roomType,
            price: formData.price,
            status: formData.status,
            hotelID: formData.hotelID
          })
          ElMessage.success('添加房间成功')
        }
        dialogVisible.value = false
        fetchRooms() // 刷新列表
      } catch (error: any) {
        ElMessage.error(error.message || (isEdit.value ? '更新房间失败' : '添加房间失败'))
      }
    }
  })
}

// 删除房间
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该房间吗？此操作将不可逆', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRoom(row.roomID)
      ElMessage.success('删除房间成功')
      fetchRooms() // 刷新列表
    } catch (error: any) {
      ElMessage.error(error.message || '删除房间失败')
    }
  }).catch(() => {
    // 取消删除，不做任何操作
  })
}

// 房间状态标签类型
const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    '空闲': 'success',
    '已预订': 'warning',
    '已入住': 'info',
    '维修中': 'danger'
  }
  return map[status] || 'success'
}
</script>

<template>
  <div class="rooms-container">
    <div class="page-header">
      <div class="header-left">
        <el-button size="small" icon="el-icon-back" @click="backToHotels">返回</el-button>
        <h2>{{ hotelInfo.name }} - 房间管理</h2>
      </div>
      <el-button type="primary" @click="handleAdd">添加房间</el-button>
    </div>
    <div class="hotel-info">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="酒店名称">{{ hotelInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ hotelInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="星级">
          <el-rate
            v-model="hotelInfo.starRating"
            disabled
            text-color="#ff9900"
          />
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="rooms-list">
      <el-table 
        :data="roomList" 
        style="width: 100%" 
        v-loading="loading"
        border
      >
        <el-table-column prop="roomID" label="房间ID" width="100" />
        <el-table-column prop="roomType" label="房间类型" />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑房间对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="房间类型" prop="roomType">
          <el-input v-model="formData.roomType" placeholder="请输入房间类型"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="formData.price" :min="0" :precision="2" :step="10" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择房间状态">
            <el-option 
              v-for="item in roomStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.rooms-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.hotel-info {
  margin-bottom: 20px;
}

.rooms-list {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 